<template>
  <div>
    <nav-bar :title="title" :isShow="false"></nav-bar>
    <van-tabs v-model="tabActive" id="tabs">
      <van-tab title="积分赠送明细">
        <form action="/">
          <van-search
            v-model="bonusQuery.name"
            clearable
            show-action
            placeholder="请输入搜索姓名"
            @search="onSearch"
            @cancel="onCancel"
          />
          <van-field
            style="padding-left: 23px"
            left-icon="calendar-o"
            clickable
            readonly
            name="calendar"
            :value="range_date"
            placeholder="点击选择日期"
            @click="showCalendar = true"
            clearable
          />
        </form>
        <van-calendar
          type="range"
          v-model="showCalendar"
          :min-date="minDate"
          @confirm="onConfirm"
        />
        <van-cell-group>
          <van-cell title="积分合计" value="">
            <template>
              <van-tag type="success">{{ bonusScores.scores }}</van-tag>
              <span v-if="bonusScores.unused_scores != 0">
                +
                <van-tag type="warning">{{
                  bonusScores.unused_scores
                }}</van-tag></span
              >
            </template>
          </van-cell>
        </van-cell-group>
        <van-list
          v-model="bonusLoading"
          :finished="bonusFinished"
          finished-text="没有更多了"
          @load="onBonusLoad"
        >
          <van-cell-group>
            <van-swipe-cell v-for="item in bonus" :key="item.id">
              <van-cell
                :title="item.customer_name"
                :value="item.score + '积分'"
                :label="item.update_time"
                :key="item.id"
              >
                <template #title>
                  <span>{{ item.customer_name }}</span>
                  <span
                    v-if="
                      item.status == 0 && item.score + item.unused_score > 0
                    "
                  >
                    <van-tag type="danger">{{
                      item.status_name
                    }}</van-tag></span
                  >
                </template>
                <template>
                  <span>{{ item.score }}</span>
                  <span v-if="item.unused_score != 0">
                    +
                    <van-tag type="warning">{{
                      item.unused_score
                    }}</van-tag></span
                  >
                </template>
                <template #label>
                  <div
                    style="
                      display: flex;
                      justify-content: space-between;
                      height: 30px;
                    "
                  >
                    <span> {{ item.name }}</span>
                    <span v-if="item.branch"> {{ item.branch }}</span>
                    <span>{{ item.update_time }}</span>
                  </div>
                </template>
              </van-cell>
              <template #right v-if="item.cancel_flag && item.status === 1">
                <van-button
                  square
                  text="取消赠送"
                  class="swipe-cell-button"
                  type="danger"
                  @click="onPointCancel(item.id)"
                />
              </template>
            </van-swipe-cell>
          </van-cell-group>
        </van-list>
      </van-tab>
      <van-tab title="积分充值明细">
        <form action="/">
          <van-field
            style="padding-left: 23px"
            left-icon="calendar-o"
            clickable
            readonly
            name="calendar"
            :value="range_date1"
            placeholder="点击选择日期"
            @click="showCalendar1 = true"
            clearable
          />
        </form>
        <van-calendar
          type="range"
          v-model="showCalendar1"
          :min-date="minDate"
          @confirm="onConfirm1"
        />
        <van-cell-group>
          <van-cell
            title="积分/充值合计"
            value=""
          >
          <template>
            {{recordScores.scores}}/ ¥{{recordScores.cash_fees}}
          </template>
          </van-cell>
        </van-cell-group>
        <van-list
          v-model="loading"
          :finished="finished"
          finished-text="没有更多了"
          @load="onLoad"
        >
          <van-cell-group>
            <van-cell
              v-for="item in records"
              :title="item.score + ' / ¥' + item.cash_fee"
              :value="item.pay_time"
              :label="item.out_trade_no"
              :key="item.id"
            >
            </van-cell>
          </van-cell-group>
        </van-list>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
// import { mapGetters } from "vuex";
import NavBar from "@/components/NavBar";
import { formatDateTime } from "@/utils/datetime";

import {
  getRechargeRecord,
  getWxBonusPointList,
  WxBonusPointCancel,
  getBonusStats,
  getRechargeStats,
} from "@/api/member";

export default {
  name: "Bill",
  components: {
    NavBar,
  },
  computed: {
    minDate() {
      let datetime = new Date();
      datetime = datetime.setFullYear(datetime.getFullYear() - 5);
      return new Date(datetime);
    },
  },
  props: ["retailer_id"],
  data() {
    return {
      title: this.$route.meta.title,
      showCalendar: false,
      showCalendar1: false,
      loading: false,
      finished: false,
      bonusLoading: false,
      bonusFinished: false,
      tabActive: 0,
      records: [],
      bonus: [],
      range_date: null,
      range_date1: null,
      bonusScores: {},
      recordScores: {},

      recordQuery: {
        page: 1,
        page_size: 10,
        retailer_id: null,
        begin_date: null,
        end_date: null,
      },
      bonusQuery: {
        page: 1,
        page_size: 10,
        retailer_id: null,
        name: null,
        begin_date: null,
        end_date: null,
      },
    };
  },
  mounted() {},
  methods: {
    onLoad() {
      this.getRecords();
      this.getRechargeStatsData();
    },
    onBonusLoad() {
      this.getBonusList();
      this.getBonusStatsData();
    },
    getRecords() {
      this.recordQuery.retailer_id = this.retailer_id;
      getRechargeRecord(this.recordQuery)
        .then((res) => {
          if (res.data.results.length === 0) {
            this.records = []; // 清空数组
            this.finished = true; // 停止加载
          }
          this.recordQuery.page = res.data.page;
          this.records.push(...res.data.results);
          this.loading = false;

          if (this.records.length >= res.data.count) {
            this.finished = true; // 结束加载状态
          }
        })
        .catch(() => {
          this.$toast("获取数据失败!");
        });
    },
    getBonusList() {
      this.bonusQuery.retailer_id = this.retailer_id;
      getWxBonusPointList(this.bonusQuery)
        .then((res) => {
          if (res.data.results.length === 0) {
            this.bonus = []; // 清空数组
            this.bonusFinished = true; // 停止加载
          }
          this.bonusQuery.page = res.data.page;
          this.bonus.push(...res.data.results);
          this.bonusLoading = false;

          if (this.bonus.length >= res.data.count) {
            this.bonusFinished = true; // 结束加载状态
          }
        })
        .catch(() => {
          this.$toast("获取数据失败!!");
        });
    },
    onSearch() {
      // console.log(val);
      this.bonus = [];
      this.bonusQuery.page=1
      this.onBonusLoad();
    },
    onCancel() {
      this.bonus = [];
      this.range_date = null;
      this.bonusQuery.end_date = null;
      this.bonusQuery.begin_date = null;
      this.bonusQuery.page=1
      this.onBonusLoad();
    },
    onConfirm(date) {
      const [start, end] = date;
      this.showCalendar = false;
      const begin_date = formatDateTime(start, "YYYY-MM-DD");
      const end_date = formatDateTime(end, "YYYY-MM-DD");
      this.bonusQuery.begin_date = begin_date;
      this.bonusQuery.end_date = end_date;
      this.range_date = `${begin_date} / ${end_date}`;
      this.bonus = [];
      this.bonusQuery.page=1
      this.onBonusLoad();
    },
    onConfirm1(date) {
      const [start, end] = date;
      this.showCalendar1 = false;
      const begin_date = formatDateTime(start, "YYYY-MM-DD");
      const end_date = formatDateTime(end, "YYYY-MM-DD");
      this.recordQuery.begin_date = begin_date;
      this.recordQuery.end_date = end_date;
      this.range_date1 = `${begin_date} / ${end_date}`;
      this.records = [];
      this.recordQuery.page = 1;
      this.onLoad();
    },
    // onPointDel(id) {
    //   console.log("point:", id);
    //   delWxBonusPoint(id)
    //     .then((res) => {
    //       console.log(res);
    //       this.$notify({
    //         type: "success",
    //         message: "取消赠送积分成功!",
    //       });
    //       this.bonus = [];
    //       this.onBonusLoad();
    //     })
    //     .catch((error) => {
    //       console.log(error);
    //       this.$notify({
    //         type: "danger",
    //         message: "取消赠送积分失败!",
    //       });
    //     });
    // },
    onPointCancel(id) {
      console.log("point:", id);
      const data = {
        bp_id: id,
        retailer_id: this.retailer_id,
      };
      WxBonusPointCancel(data)
        .then((res) => {
          console.log(res);
          this.$notify({
            type: "success",
            message: "取消积分成功!",
          });
          this.bonus = [];
          this.onBonusLoad();
        })
        .catch((error) => {
          console.log(error);
          this.$notify({
            type: "danger",
            message: "取消积分失败!",
          });
        });
    },
    getBonusStatsData() {
      getBonusStats(this.bonusQuery)
        .then((res) => {
          this.bonusScores = res.data;
          console.log("res=", res);
        })
        .catch((error) => {
          console.log(error);
        });
    },
    getRechargeStatsData() {
      getRechargeStats(this.recordQuery)
        .then((res) => {
          this.recordScores = res.data;
          console.log("res=", res);
        })
        .catch((error) => {
          console.log(error);
        });
    },
  },
};
</script>

<style  scoped>
.van-swipe-cell .van-cell__title {
  flex: 4;
}
</style>